﻿using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using cn.sharesdk.unity3d;
using UnityEngine.UI;
using tools;
using info;
using UnityEngine.SceneManagement;
public class Demo : MonoBehaviour {

	public Button LoginBtn;
	/// <summary>
    ///share android link 
    /// </summary>
	//public Button ShareAndroidBtn;
	/// <summary>
    ///share android image 
    /// </summary>
	//public Button ShareImageAndroidBtn;
	/// <summary>
    ///share ios link 
    /// </summary>
	//public Button ShareIosBtn;
	/// <summary>
    ///share ios image  
    /// </summary>
	//public Button ShareImageIosBtn;
	public Text TextInfo;
	//public RawImage headerTex;
	public ShareSDK ssdk;
	private int reskTime = 0;
	public static bool reLogin = false;
	// Use this for initialization
	void Start ()
	{	
		ssdk = gameObject.GetComponent<ShareSDK>();
		ssdk.authHandler = OnAuthResultHandler;
		ssdk.shareHandler = OnShareResultHandler;
		ssdk.showUserHandler = OnGetUserInfoResultHandler;
		ssdk.getFriendsHandler = OnGetFriendsResultHandler;
		ssdk.followFriendHandler = OnFollowFriendResultHandler;

	
		if (LoginBtn != null) {
			LoginBtn.onClick.AddListener (doWeiChatLogin);
		}

		DontDestroyOnLoad (gameObject);

		//ShareAndroidBtn.onClick.AddListener (doWeiChatShareText4Android);
		//ShareIosBtn.onClick.AddListener (doWeiChatShareText4IOS);

		//ShareImageAndroidBtn.onClick.AddListener(doWeiChatShareImageAndroid);
		//ShareImageIosBtn.onClick.AddListener(doWeiChatShareImageIOS);

		Copy2SDpath ();

	}

	public void WXPayCallback(string CodeID){
		Debug.Log ("CodeID---------------------------:"+CodeID);
		if (CodeID == "-2") {
			//支付取消
		} else if (CodeID == "0") {
			//支付成功
		}
	}

	// Update is called once per frame
	void Update () 
	{
		reskTime--;
		if (SceneManager.GetActiveScene ().buildIndex == 1) {
			if (reskTime > 0) {
				if (GameObject.Find ("assyoufuck") != null) {
					GameObject.Find ("assyoufuck").transform.localPosition = Vector3.zero;
				}
			} else {
				if (GameObject.Find ("assyoufuck") != null) {
					GameObject.Find ("assyoufuck").transform.localPosition = new Vector3(10000,10000,0);
				}
			}
		}

		if (Input.GetKeyDown(KeyCode.Escape)) {
			Application.Quit();
		}
	}

	private void doWeiChatLogin(){

		if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer) {
			//PC测试用
			string[] str = new string[4];
			str [0] = "USER_"+MyRandom.getRandom (0, 100000000);
			info.UserInfo.OpenID = str [0];
			str [1] = str [0];
			str [2] = "1";
			str [3] = str [0];
			GSocket.Send (ByteFactory.makeByte (100101, str));
			return;
		}
	

		if (reskTime > 0) {
			return;
		}
		reskTime = 1000;
		cashDataLoader cash = new cashDataLoader ();
		string data = cash.LoadNotice ();

		if ( data != null ) {
			string[] datas = data.Split (',');
			GSocket.Send (ByteFactory.makeByte (100101, datas));
			return;
		}


		ssdk.Authorize(PlatformType.WeChat);
	}
	
	private void doWeiChatGetUserInfo(){
		Debug.Log ("doWeiChatGetUserInfo");
		ssdk.GetUserInfo(PlatformType.WeChat);
	}
	/// <summary>
    ///分享ios图片 
    /// </summary>
	private void doWeiChatShareImageIOS(){
		return;
		ScreenShotShare.onShotFinishedCallBack = delegate(){
			ShareContent content = new ShareContent();
			content.SetText("快来和我一起炸金花!!!!!");
			string imagePath = ScreenShotShare.shotPath;  
			content.SetImagePath (imagePath);
			content.SetUrl("http://fir.im/6klz");
			content.SetTitle("友友炸金花");
			content.SetShareType(ContentType.Image);
			ssdk.ShareContent(PlatformType.WeChat,content);
		};
		ScreenShotShare.BeginShotNow(this);

		
	}
	/// <summary>
    ///分享Android图片 
    /// </summary>
	public void doWeiChatShareImageAndroid(){
		doWeiChatShareImageIOS();
	}
	private void Copy2SDpath()  
	{  
		//读、写的路径          
		string imagePath = Application.persistentDataPath + "/share.png";  
		//如果文件不存在，把它拷贝进去。  
		if (!System.IO.File.Exists(imagePath))  
		{  
			if (Application.platform == RuntimePlatform.IPhonePlayer) {

				Texture2D o = Resources.Load("Icon-256") as Texture2D;  
				if (o != null)  
				{  
					System.IO.File.WriteAllBytes(imagePath, o.EncodeToPNG());  
				} 
			}
		}  
	}  
	string shareText = "房间号：{0},{1},{2}局，速度加入【友友炸金花】";
	public void doWeiChatShareText4IOS(){
		return;
		ShareContent content = new ShareContent();
		content.SetText(string.Format (shareText,UserInfo.room.roomId.ToString(),"炸金花",+UserInfo.room.seats.Count+"人"+UserInfo.room.rounds.ToString(),""));
		string imagePath = Application.persistentDataPath + "/share.png";
		content.SetImagePath (imagePath);
		content.SetTitle("大家一起来炸金花");
		content.SetUrl("http://fir.im/6klz");
		content.SetComment("test description");
		content.SetShareType(ContentType.Webpage);
		ssdk.ShareContent(PlatformType.WeChat,content);
	}

	public void CallAndroid(string args){
		//AndroidJavaClass ajc = new AndroidJavaClass("com.geek.hyzjh.mm.wxapi.WXPayEntryActivity");
		//AndroidJavaObject ajo = ajc.GetStatic<AndroidJavaObject>("currentActivity");
		//ajc.Call ("WXPays");
		Debug.Log(args);
	}
		
	public void doWeiChatShareFor4(){
		return;
		ShareContent content = new ShareContent();

		content.SetText("大家一起来炸金花");
		string imagePath = Application.persistentDataPath + "/share.png";
		content.SetImagePath (imagePath);
		content.SetTitle("大家一起来炸金花");
		content.SetUrl("http://fir.im/6klz");
		content.SetComment("test description");
		content.SetShareType(ContentType.Webpage);
		ssdk.ShareContent(PlatformType.WeChat,content);
	}

	private void doWeiChatShareText4Android(){
		doWeiChatShareText4IOS();
	}

	void OnGUI ()
	{


		float scale = 1.0f;

		if (Application.platform == RuntimePlatform.IPhonePlayer)
		{
			scale = Screen.width / 320;
		}
		
		float btnWidth = 165 * scale;
		float btnHeight = 30 * scale;
		float btnTop = 20 * scale;
		float btnGap = 20 * scale;
		GUI.skin.button.fontSize = Convert.ToInt32(14 * scale);


			


//		btnTop += btnHeight + 20 * scale;
//		if (GUI.Button(new Rect((Screen.width - btnGap) / 2 - btnWidth, btnTop, btnWidth, btnHeight), "Show Share Menu"))
//		{
//			ShareContent content = new ShareContent();
//			content.SetText("this is a test string.");
//			content.SetImageUrl("https://f1.webshare.mob.com/code/demo/img/1.jpg");
//			content.SetTitle("test title");
//			content.SetTitleUrl("http://www.mob.com");
//			content.SetSite("Mob-ShareSDK");
//			content.SetSiteUrl("http://www.mob.com");
//			content.SetUrl("http://www.mob.com");
//			content.SetComment("test description");
//			content.SetMusicUrl("http://mp3.mwap8.com/destdir/Music/2009/20090601/ZuiXuanMinZuFeng20090601119.mp3");
//			content.SetShareType(ContentType.Image);
//
//			//不同平台分享不同内容
//			ShareContent customizeShareParams = new ShareContent();
//			customizeShareParams.SetText("Sina share content");
//			customizeShareParams.SetImageUrl("http://git.oschina.net/alexyu.yxj/MyTmpFiles/raw/master/kmk_pic_fld/small/107.JPG");
//			customizeShareParams.SetShareType(ContentType.Image);
//			customizeShareParams.SetObjectID("SinaID");
//			content.SetShareContentCustomize(PlatformType.SinaWeibo, customizeShareParams);
//
//			//通过分享菜单分享
//			ssdk.ShowPlatformList (null, content, 100, 100);
//		}
//			
//		if (GUI.Button(new Rect((Screen.width - btnGap) / 2 + btnGap, btnTop, btnWidth, btnHeight), "Show Share View"))
//		{
//			ShareContent content = new ShareContent();
//			content.SetText("this is a test string.");
//			content.SetImageUrl("https://f1.webshare.mob.com/code/demo/img/1.jpg");
//			content.SetTitle("test title");
//			content.SetTitleUrl("http://www.mob.com");
//			content.SetSite("Mob-ShareSDK");
//			content.SetSiteUrl("http://www.mob.com");
//			content.SetUrl("http://www.mob.com");
//			content.SetComment("test description");
//			content.SetMusicUrl("http://mp3.mwap8.com/destdir/Music/2009/20090601/ZuiXuanMinZuFeng20090601119.mp3");
//			content.SetShareType(ContentType.Image);
//
//			ssdk.ShowShareContentEditor (PlatformType.SinaWeibo, content);
//		}
//
//		btnTop += btnHeight + 20 * scale;
//		if (GUI.Button(new Rect((Screen.width - btnGap) / 2 - btnWidth, btnTop, btnWidth, btnHeight), "Share Content"))
//		{
//			ShareContent content = new ShareContent();
//			content.SetText("this is a test string.");
//			content.SetImageUrl("https://f1.webshare.mob.com/code/demo/img/1.jpg");
//			content.SetTitle("test title");
//			content.SetTitleUrl("http://www.mob.com");
//			content.SetSite("Mob-ShareSDK");
//			content.SetSiteUrl("http://www.mob.com");
//			content.SetUrl("http://www.mob.com");
//			content.SetComment("test description");
//			content.SetMusicUrl("http://mp3.mwap8.com/destdir/Music/2009/20090601/ZuiXuanMinZuFeng20090601119.mp3");
//			content.SetShareType(ContentType.Image);
//			ssdk.ShareContent (PlatformType.WeChat, content);
//		}
//			
//		if (GUI.Button(new Rect((Screen.width - btnGap) / 2 + btnGap, btnTop, btnWidth, btnHeight), "Get Friends SinaWeibo "))
//		{
//			//获取新浪微博好友，第一页，每页15条数据
//			Debug.Log ("Click Btn Of Get Friends SinaWeibo");
//			ssdk.GetFriendList (PlatformType.WeChat, 15, 0);
//		}
//
//		btnTop += btnHeight + 20 * scale;
//		if (GUI.Button(new Rect((Screen.width - btnGap) / 2 - btnWidth, btnTop, btnWidth, btnHeight), "Get Token SinaWeibo "))
//		{
//			Hashtable authInfo = ssdk.GetAuthInfo (PlatformType.WeChat);			
//			Debug.Log ("share result :");
//			Debug.Log (MiniJSON.jsonEncode(authInfo));
//		}
//			
//		if (GUI.Button(new Rect((Screen.width - btnGap) / 2 + btnGap , btnTop, btnWidth, btnHeight), "Close SSO Auth"))
//		{
//			ssdk.DisableSSO (true);			
//		}
//
//		btnTop += btnHeight + 20 * scale;
//		if (GUI.Button(new Rect((Screen.width - btnGap) / 2 - btnWidth, btnTop, btnWidth, btnHeight), "Remove Authorize "))
//		{
//			ssdk.CancelAuthorize (PlatformType.SinaWeibo);			
//		}
//			
//		if (GUI.Button(new Rect((Screen.width - btnGap) / 2 + btnGap, btnTop, btnWidth, btnHeight), "Add Friend "))
//		{
//			//关注新浪微博
//			ssdk.AddFriend (PlatformType.SinaWeibo, "3189087725");			
//		}
//
//		btnTop += btnHeight + 20 * scale;
//		if (GUI.Button(new Rect((Screen.width - btnGap) / 2 - btnWidth, btnTop, btnWidth, btnHeight), "ShareWithContentName"))
//		{
//			Hashtable customFields = new Hashtable ();
//			customFields["imgUrl"] = "http://ww1.sinaimg.cn/mw690/006dJESWgw1f6iyb8bzraj31kw0v67a2.jpg";
//			//根据配置文件分享【本接口功能仅暂时支持iOS】
//			ssdk.ShareWithContentName(PlatformType.SinaWeibo, "mob", customFields);		
//		}

	}

	/// <summary>
	/// 授权登录
	/// </summary>
	/// <param name="reqID">Req I.</param>
	/// <param name="state">State.</param>
	/// <param name="type">Type.</param>
	/// <param name="result">Result.</param>
	void OnAuthResultHandler(int reqID, ResponseState state, PlatformType type, Hashtable result)
	{
		Debug.Log ("state:"+state);
		if (state == ResponseState.Success)
		{
			Debug.Log ("authorize success !" + "Platform :" + type);
			//获取用户信息
			this.doWeiChatGetUserInfo ();
		}
		else if (state == ResponseState.Fail)
		{
			#if UNITY_ANDROID
			Debug.Log ("fail! throwable stack = " + result["stack"] + "; error msg = " + result["msg"]);
			#elif UNITY_IPHONE
			Debug.Log ("fail! error code = " + result["error_code"] + "; error msg = " + result["error_msg"]);
			#endif
		}
		else if (state == ResponseState.Cancel) 
		{
			Debug.Log ("cancel !");
		}
	}
	/// <summary>
	/// 获取微信用户信息
	/// </summary>
	/// <param name="reqID">Req I.</param>
	/// <param name="state">State.</param>
	/// <param name="type">Type.</param>
	/// <param name="result">Result.</param>
	void OnGetUserInfoResultHandler (int reqID, ResponseState state, PlatformType type, Hashtable result)
	{
		Debug.Log ("fail! throwable stack = " + result["stack"] + "; error msg = " + result["msg"]);
		if (state == ResponseState.Success)
		{
			Debug.Log ("get user info result :");
			string info = MiniJSON.jsonEncode (result);
			string nickName = result["nickname"].ToString();
			string openId = result["openid"].ToString();
			string sex = result["sex"].ToString();//1 男 0 女
			string headImg = result["headimgurl"].ToString();

			Debug.Log (info);
			//StartCoroutine ( LoadTexture((string)result["headimgurl"],onGotHeader) );

			string[] str = new string[4];
			str [0] = openId;
			UserInfo.OpenID = openId;
			str [1] = nickName;
			str [2] = sex;
			str [3] = headImg;
			cashDataLoader cash = new cashDataLoader ();
			cash.CreateFile ("user.txt",str [0]+","+str [1]+","+str [2]+","+str [3]);
			GSocket.Send (ByteFactory.makeByte (100101, str));
		}
		else if (state == ResponseState.Fail)
		{
			#if UNITY_ANDROID
			Debug.Log ("fail! throwable stack = " + result["stack"] + "; error msg = " + result["msg"]);
			#elif UNITY_IPHONE
			Debug.Log ("fail! error code = " + result["error_code"] + "; error msg = " + result["error_msg"]);
			#endif
		}
		else if (state == ResponseState.Cancel) 
		{
			Debug.Log ("cancel !");
		}
	}

	private void onGotHeader(Texture2D obj) {
		//headerTex.texture = obj;
	}

	IEnumerator LoadTexture(string url,Action<Texture2D> cb)  
	{  
		//这里的url可以是web路径也可以是本地路径file://  
		WWW www = new WWW (url);  
		//挂起程序段，等资源下载完成后，继续执行下去  
		yield return www;  

		//判断是否有错误产生  
		if (string.IsNullOrEmpty (www.error)) {      
			//把下载好的图片回调给调用者  
			cb.Invoke (www.texture);  
			//释放资源  
			www.Dispose ();  
		}  
	}  
	
	void OnShareResultHandler (int reqID, ResponseState state, PlatformType type, Hashtable result)
	{
		if (state == ResponseState.Success)
		{
			Debug.Log ("share successfully - share result :");
			Debug.Log (MiniJSON.jsonEncode(result));
		}
		else if (state == ResponseState.Fail)
		{
			#if UNITY_ANDROID
			Debug.Log ("fail! throwable stack = " + result["stack"] + "; error msg = " + result["msg"]);
			#elif UNITY_IPHONE
			Debug.Log ("fail! error code = " + result["error_code"] + "; error msg = " + result["error_msg"]);
			#endif
		}
		else if (state == ResponseState.Cancel) 
		{
			Debug.Log ("cancel !");
		}
	}

	void OnGetFriendsResultHandler (int reqID, ResponseState state, PlatformType type, Hashtable result)
	{
		if (state == ResponseState.Success)
		{			
			Debug.Log ("get friend list result :");
			Debug.Log (MiniJSON.jsonEncode(result));
		}
		else if (state == ResponseState.Fail)
		{
			#if UNITY_ANDROID
			Debug.Log ("fail! throwable stack = " + result["stack"] + "; error msg = " + result["msg"]);
			#elif UNITY_IPHONE
			Debug.Log ("fail! error code = " + result["error_code"] + "; error msg = " + result["error_msg"]);
			#endif
		}
		else if (state == ResponseState.Cancel) 
		{
			Debug.Log ("cancel !");
		}
	}

	void OnFollowFriendResultHandler (int reqID, ResponseState state, PlatformType type, Hashtable result)
	{
		if (state == ResponseState.Success)
		{
			Debug.Log ("Follow friend successfully !");
		}
		else if (state == ResponseState.Fail)
		{
			#if UNITY_ANDROID
			Debug.Log ("fail! throwable stack = " + result["stack"] + "; error msg = " + result["msg"]);
			#elif UNITY_IPHONE
			Debug.Log ("fail! error code = " + result["error_code"] + "; error msg = " + result["error_msg"]);
			#endif
		}
		else if (state == ResponseState.Cancel) 
		{
			Debug.Log ("cancel !");
		}
	}
}
